
#include <Audio\AudioFileOut.h>
#include <Config\ParserFileName.h>
#include <regex>
using namespace audio;
#pragma warning(disable:4996)
namespace audio {		// begin library specific namespace
	AudioFileOut::AudioFileOut(const AudioFileOut &src){

	}
	AudioFileOut::AudioFileOut(PaserName &name, Option &option, LENGTH_TYPE legth, LENGTH_TYPE resplution, LENGTH_TYPE samplerate, std::string dir) : AudioFile(){
		this->dir = dir;
		this->legth = legth;
		this->resplution = resplution;
		this->samplerate = samplerate;
		this->paserName = &name;
		this->option = &option;
	}

	AudioFileOut::AudioFileOut(AudioFile &src, PaserName &name, Option &option, std::string dir) : AudioFile(){
		this->paserName = &name;
		this->option = &option;
		this->dir = dir;
		this->legth = src.GetSize();
		this->resplution = src.GetResolution();
		this->samplerate = src.GetRate();

	}


	void AudioFileOut::AddChannel(float *dataCh){
		channels.push_back(dataCh);
	}


	void AudioFileOut::Save(){
		
		std::string path = getNewName();

		if (legth > 0 && channels.size() > 0 && samplerate > 0){

			//Create Audio
			AudioFile::Create(this->legth, channels.size(), this->resplution, this->samplerate);

			//Copy all channel
			for (unsigned int ch = 0; ch < channels.size(); ch++){
				float * chan = AudioFile::GetSafePt(ch, true);
				memcpy(chan, channels[ch], legth *sizeof(float));
			}
			//Save audio
			AudioFile::SaveWave(const_cast<char *>(path.c_str()));

		}

	}


	void AudioFileOut::Save(std::string name){
		//Create Audio
		//std::string  path = dir + name;
		//this->Savepath);
	}

	// Ham huy
	AudioFileOut::~AudioFileOut(){

		/*for (unsigned int ch = 0; ch < channels.size(); ch++){
			float * chan = channels.back();
			channels.pop_back();
			if (chan){
				delete[] chan;
			}
		}*/

	}



	std::string AudioFileOut::getNewName(){
		std::string newname = "";
		/*try{
			name = std::string(path);
		}
		catch (...){}

		std::regex match("(.+\\\\)?(.+)(\\.[\\w\\d]+)");

		std::string dir = std::regex_replace(name, match, "$1");
		std::string file = std::regex_replace(name, match, "$2");
		std::string ext = std::regex_replace(name, match, "$3");
*/
		newname = "";
		
		if (option->AddPrefixName && option->PrefixName.length() > 0){
			newname += option->PrefixName;
		}

		newname += paserName->getName();
		if (option->AddAvgName){
			char pre[200] = { 0 };
			sprintf(pre, "`f=%3.9f", avg_frequency);
			newname += std::string(pre);
		}

		if (option->MovetoNewFolder){
			newname = option->OutputDir + "\\" + newname;
		}
		else
			newname = paserName->getDir() + newname;

		newname += paserName->getExt();

		return newname;
	}


	void AudioFileOut::setAvgFrequency(float avg){
		avg_frequency = avg;
	}
}	// end library specific namespace
